<template>
  <a-modal
    :visible="modalVisible"
    :title="modalTitle"
    @cancel="handleCancel(0)"
    :footer="null"
    width="700px"
    :afterClose="afterColseModal"
  >
    <a-form-model layout="inline" :model="form" :rules="formRules" ref="formRef">
      <!-- 修改手机号 -->
      <a-row :gutter="48" v-if="isPhone">
        <a-col :md="18" :sm="24">
          <a-form-model-item label="手机号" prop="phone">
            <a-input v-model="form.phone" placeholder="请输入手机号" style="width: 350px" />
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item>
            <a-button type="primary" :loading="varLoading" @click="clickPhoneCode()" :disabled="isDisabled" v-if="!isDisabled">获取验证码</a-button>
            <a-button type="primary" v-else :disabled="isDisabled">{{ timeValue }}秒后再次点击</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="48" v-if="isPhone" style="margin-top: 20px">
        <a-col :md="18" :sm="24">
          <a-form-model-item label="验证码" prop="pin">
            <a-input v-model="form.pin" placeholder="请输入验证码" :disabled="!isSend" style="width: 350px" />
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item>
            <a-button type="primary" :loading="submitting" :disabled="!isSend" @click="clickPhoneCode('pin')">绑定手机号</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 修改邮箱 -->
      <a-row :gutter="48" v-if="!isPhone">
        <a-col :md="18" :sm="24">
          <a-form-model-item label="邮箱号" prop="email">
            <a-input v-model="form.email" placeholder="请输入邮箱号" style="width: 350px" />
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item>
            <a-button type="primary" :loading="varLoading" @click="clickEmailCode()" v-if="!isDisabled">获取验证码</a-button>
            <a-button type="primary"  v-else :disabled="isDisabled">{{ timeValue }}秒后再次点击</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="48" v-if="!isPhone" style="margin-top: 20px">
        <a-col :md="18" :sm="24">
          <a-form-model-item label="验证码" prop="pin">
            <a-input v-model="form.pin" placeholder="请输入验证码" :disabled="!isSend" style="width: 350px" />
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item>
            <a-button type="primary" :loading="submitting" :disabled="!isSend" @click="clickEmailCode('pin')">绑定邮箱</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </a-modal>
</template>

<script>
import monitor from '@/utils/monitor'
import modal from '@/monitor/views/account/settings/modal.js'

import { getVerificationCode, sendPhoneCode, getEmailCode, sendEmailCode } from '@/api/common'

const watch = monitor(modal)

export default {
  components: {
  },
  props: {
    modalTitle: {
      type: String,
      default: ''
    },
    modalVisible: {
      type: Boolean,
      default: false
    },
    isPhone: {
      type: Boolean,
      default: true
    },
    phoneNumber: {
      type: [Number, String],
      default: null
    }
  },
  data () {
    return {
      isSend: false,
      isDisabled: false,
      timeValue: 60,
      userPhone: null, // 点击获取验证码时将此时输入框中的号码进行存储
      userEmail: null, // 点击获取验证码时将此时输入框中的邮箱进行存储
      form: {},
      formRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号格式错误' }
        ],
        pin: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          { pattern: /^\d{6}\b/, message: '验证码格式错误' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          { pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '邮箱格式错误' }
        ]
      },
      interval: null, // 定时器
      varLoading: false,
      submitting: false
    }
  },
  methods: watch({
    // 点击获取/发送手机验证码（更改手机号）
    clickPhoneCode (type = 'phone') {
      this.$refs.formRef.validateField([type], valid => {
        if (!valid) {
          if (type === 'pin') {
            this.sendPhoneCode()
          } else {
            this.getPhoneCode()
          }
        }
      })
    },
    // 获取手机验证码的请求（更改手机号）
    getPhoneCode () {
      this.varLoading = true
      getVerificationCode({ phone: this.form.phone })
        .then(res => {
          this.varLoading = false
          this.$message.success('验证码已发送')
          this.userPhone = this.form.phone
          this.isSend = true
          this.isDisabled = !this.isDisabled
          this.setTime()
        })
        .catch(() => {
          this.varLoading = false
        })
    },
    // 发送手机验证码的请求（更改手机号）
    sendPhoneCode () {
      this.submitting = true
      sendPhoneCode({ newPhone: this.userPhone, newCode: this.form.pin })
        .then(res => {
          this.submitting = false
          this.$message.success('手机号码更改成功')
          // this.$emit('closeModal')
          this.handleCancel(1)
          this.changePhone()
        })
        .catch(() => {
          this.submitting = false
        })
    },
    // 点击获取/发送手机验证码（绑定邮箱）
    clickEmailCode (type = 'email') {
      this.$refs.formRef.validateField([type], valid => {
        if (!valid) {
          if (type === 'pin') {
            this.sendEmailCode()
          } else {
            this.getEmailCode()
          }
        }
      })
    },
    // 获取手机验证码的请求（绑定/更改邮箱）
    getEmailCode () {
      // getVerificationCode({ phone: this.phoneNumber })
      this.varLoading = true
      getEmailCode({ email: this.form.email })
        .then(res => {
          this.varLoading = false
          this.$message.success('验证码已发送')
          this.userEmail = this.form.email
          this.isSend = true
          this.isDisabled = !this.isDisabled
          this.setTime()
        })
        .catch(() => {
          this.varLoading = true
        })
    },
    // 定时器 1分钟
    setTime () {
      this.timeValue = 60
      this.interval && clearInterval(this.interval)
      this.interval = setInterval(() => {
        console.log('this.timeValue', this.timeValue)
        this.timeValue -= 1
        if (this.timeValue < 0) {
          this.isDisabled = !this.isDisabled
          clearInterval(this.interval)
        }
      }, 1000)
    },
    // 发送手机验证码的请求（绑定/更改邮箱）
    sendEmailCode () {
      this.submitting = true
      sendEmailCode({ newEmail: this.userEmail, newCode: this.form.pin })
        .then(res => {
          this.submitting = false
          if (this.modalTitle === '绑定邮箱') {
            this.$message.success('邮箱绑定成功')
          } else {
            this.$message.success('邮箱更改成功')
            this.changeEmail()
          }
          // this.$emit('closeModal')
          this.handleCancel(1)
        })
        .catch(() => {
          this.submitting = false
        })
    },
    // 关闭弹框 重置表单
    handleCancel (val) {
      this.$emit('closeModal', val)
      setTimeout(() => {
        this.$refs.formRef.resetFields()
      }, 200)
    },
    // 更改手机号埋点
    changePhone () {},
    // 更改邮箱埋点
    changeEmail () {},
    afterColseModal () {
      this.interval && clearInterval(this.interval)
      this.isDisabled = false
    }
  })
}
</script>
<style lang="less" scoped>
  .save-button {
    margin-right: 10px;
  }
</style>
